package xyz.labmem.base.sys.context

import cn.hutool.json.JSONUtil
import org.springframework.stereotype.Repository
import xyz.labmem.base.core.consts.*
import xyz.labmem.base.core.tool.jsonToObject
import xyz.labmem.base.core.tool.toJsonStr
import xyz.labmem.base.sys.module.log.entity.SysUserOnline
import xyz.labmem.base.sys.util.RedisService
import java.util.concurrent.TimeUnit

/**
 * @Author lty
 * @Date 2021/12/16 10:17
 */
@Repository
class AuthRedisService(
    private var redis: RedisService
) {
    //存登录信息
    fun setUserEntity(user: SysUserOnline): Boolean {
        val json = user.toJsonStr()
        return if (json != null) {
                redis.add(userKeyPrefix + user.tokenId!!, json)
                true
            } else
                 false
    }
    //获取登录信息
    fun getUserEntity(id: String): SysUserOnline? {
        if (redis.isNotEmpty(userKeyPrefix+id)) {
            return redis.get(userKeyPrefix+id)?.jsonToObject(SysUserOnline::class.java)
        }
        return null
    }

    fun removeUserEntity(id: String, token:String) {
        removeUserPermission(id)
        removeUserRole(id)
        redis.delete(userKeyPrefix + token)
    }

    fun setUserPermission(id: String, permission: List<String>): Boolean {
        val json = JSONUtil.toJsonStr(permission)
        return if (json != null) {
            redis.add(permissionKeyPrefix + id, json, 60, TimeUnit.MINUTES)
            true
        } else
            false
    }

    fun getUserPermission(id: String): List<String>? {
        if (redis.isNotEmpty(permissionKeyPrefix + id)) {
            return JSONUtil.parseArray(redis.get(permissionKeyPrefix + id)).toList(String::class.java)
        }
        return null
    }

    fun removeUserPermission(id: String) {
        redis.delete(permissionKeyPrefix + id)
    }

    fun setUserRole(id: String, role: List<String>): Boolean {
        val json = JSONUtil.toJsonStr(role)
        return if (json != null) {
            redis.add(roleKeyPrefix + id, json, 60, TimeUnit.MINUTES)
            true
        } else
            false
    }

    fun getUserRole(id: String): List<String>? {
        if (redis.isNotEmpty(roleKeyPrefix + id)) {
            return JSONUtil.parseArray(redis.get(roleKeyPrefix + id)).toList(String::class.java)
        }
        return null
    }

    fun removeUserRole(id: String) {
        redis.delete(roleKeyPrefix + id)
    }

}
